package com.bwie.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.bwie.pay.config.AliPayConfig;
import com.bwie.pay.domain.AliPay;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("pay")
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class AliPayController {
//    private final AliPayConfig aliPayConfig;

//    @GetMapping("aliPay")
//    public AjaxResult aliPay() throws Exception {
//        //配置
//        Factory.setOptions(aliPayConfig.getOptions());
//        //调用支付接口
//        AlipayTradePrecreateResponse alipayTradePrecreateResponse = Factory.Payment.FaceToFace().preCreate("巧克力", "2234567", "100");
//        //获得调用结果
//        JSONObject httpBodyObject = JSON.parseObject(alipayTradePrecreateResponse.httpBody);
//        //获得图片
//        String qrCode = httpBodyObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code");
////        //在固定位置生成图片
////        QrCodeUtil.generate(qrCode, 400,400, FileUtil.file("D:/li.jpg"));
//        //生成图片规格
//        QrConfig qrConfig = new QrConfig(400,400);
//        //生成图片
//        BufferedImage generate = QrCodeUtil.generate(qrCode, qrConfig);
//        //生成结果集
//        AjaxResult ajax = AjaxResult.success();
//        //转换图片格式
//        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
//        try
//        {
//            ImageIO.write(generate, "jpg", os);
//        }
//        catch (IOException e)
//        {
//            return AjaxResult.error(e.getMessage());
//        }
//        //赋值
//        ajax.put("img", Base64.encode(os.toByteArray()));
//        //返回
//        return ajax;
//    }
//
//
//    /**
//     * 支付成功回调函数
//     */
//    @PostMapping("Result")
//    public void Result(){
//        System.out.println("等待结果");
//    }


    @Resource
    AliPayConfig aliPayConfig;


    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    @GetMapping("/pay") // 前端路径参数格式?subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            //订单号
            String tradeNo = params.get("out_trade_no");
            // 支付时间
            String gmtPayment = params.get("gmt_payment");
            // 支付宝交易凭证号
            String alipayTradeNo = params.get("trade_no");

            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单已支付的逻辑代码
                //todo

            }
        }
        return "success";
    }



}
